#include "logger.h"
#include <time.h>
#include "../stringUtil.h"
namespace TinyRPC{



char* GetLevelName(LogLevel level){
    switch (level)
    {
    case LogLevel::DEBUG:
        return (char*)"DEBUG";
        break;
    
    case LogLevel::INFO:
        return (char*)"INFO";
        break;
    case LogLevel::WARNING:
        return (char*)"WARNING";
        break;
    case LogLevel::ERROR:
        return (char*)"ERROR";
        break;
    default:
        return (char*)"UNKNOWN";
            break;
    }
}

Logger& Logger::GetInstance(){
    static Logger g_logger(LogLevel::DEBUG);
    return g_logger;
}

Logger::Logger(LogLevel level)
: m_level(level)
, m_logStream(m_ofs)
{
    m_ofs.open("./log.txt");
}
Logger::~Logger(){
    m_ofs.close();
}

void Logger::setLogLevel(LogLevel level){
    m_level = level;
}
LogLevel Logger::getLogLevel(){
    return m_level;
}

void Logger::log(std::string& str){
    str += "\n";
    m_logStream.log(str);
}
void Logger::log(std::string&& str) {
    str += "\n";
    m_logStream.log(str);
}

    
LoggerWrapper::LoggerWrapper(Logger & logger)
: m_logger(logger){}
LoggerWrapper::~LoggerWrapper(){
    m_logger.log(m_ss.str());
}
std::stringstream& LoggerWrapper::getSStream(const char* fileName, const char* funcName, int lineNo,  pid_t tid, LogLevel level){
    time_t rawtime;
    time(&rawtime);
    /* 获取 GMT 时间 */
    struct tm*  time_tm = localtime(&rawtime);

    char buf[512] = {0};

    vector<string> spiltStr;
    splitString(fileName, spiltStr, "/");
    snprintf(buf, 512, "[%d-%d-%d %d:%d:%d][%s:%s:%d][Tid:%d][%s]: ",time_tm->tm_year + 1900 , time_tm->tm_mon, time_tm->tm_mday, 
        time_tm->tm_hour, time_tm->tm_min, time_tm->tm_sec,spiltStr.back().c_str(), funcName, lineNo, tid, GetLevelName(level));
    m_ss<<std::string(buf);
    return m_ss;
}

}
